# write functions to calculate confidence intervals -----------------------

lower_ci <- function(mean, se, n, conf_level = 0.95){
  lower_ci <- mean - qt(1 - ((1 - conf_level) / 2), n - 1) * se
}

upper_ci <- function(mean, se, n, conf_level = 0.95){
  upper_ci <- mean + qt(1 - ((1 - conf_level) / 2), n - 1) * se
}

# import the fdc dataset and plot the figure ------------------------------

figure_4 <- read.csv("datasets/data_fdc.csv") %>%
  mutate(coffins_binary = if_else(coffins > 0, 1, 0)) %>%
  select(coffins_binary, akp_nov, akp_jun) %>%
  pivot_longer(names_to = "election", values_to = "vote_share", 
               cols = akp_nov:akp_jun) %>% 
  group_by(election, coffins_binary) %>%
  summarise(smean = mean(vote_share, na.rm = TRUE),
            ssd = sd(vote_share, na.rm = TRUE),
            count = n()) %>%
  mutate(se = ssd / sqrt(count),
         lower_ci = lower_ci(smean, se, count),
         upper_ci = upper_ci(smean, se, count)) %>% 
  ggplot(aes(x = election, y = smean, colour = factor(coffins_binary), 
             group = factor(coffins_binary))) +
  geom_errorbar(aes(ymin = lower_ci, ymax = upper_ci), width = 0.1, 
                position = position_dodge(0.1), linetype = "dashed", 
                size = 0.8) +
  geom_line(position = position_dodge(0.1), size = 1.2) +
  geom_point(position = position_dodge(0.1), size = 2) +
  theme_light() +
  theme(axis.line = element_line(colour = "black", size = 0.25),
        panel.grid.major = element_line(colour = "grey95", size = 0.25),
        panel.grid.minor = element_line(colour = "grey95", size = 0.125),
        panel.border = element_rect(fill = NA, colour = "grey95", 
                                      size = 0.25),
        axis.text = element_text(size = 12), 
        axis.title = element_text(size = 12),
        legend.text = element_text(size = 12),
        legend.position = "bottom") +
  labs(x = "\nElections in 2015", y = "Government vote share\n") +
  scale_x_discrete(breaks = c("akp_jun", "akp_nov"),
                   labels = c("June", "November")) +
  scale_y_continuous(labels = function(x) paste0(x, "%")) +
  scale_colour_manual(name = "Districts",
                      values = c("black", "gray60"),
                      breaks = c(1, 0),
                      labels = c("with", "without ... one or more funerals"))

# display the figure ------------------------------------------------------

print(figure_4)

# save the figure ---------------------------------------------------------

ggsave(plot = figure_4, filename = "figures/figure_4.pdf", dpi = 1000,
       width = 8.5, height = 6, units = "in")  